package controller

import (
	"appService/src/application"
	"appService/src/application/admin/admin/adminModels"
	"appService/src/application/app/appModels"
	"appService/src/authValid"
	"appService/src/authValid/dataAuth"
	"appService/src/orm"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"xorm.io/builder"
)

//Auth 菜单权限
type Auth struct {
	application.BaseController
}

//getModel 获取控制器对应的 模型
func  (*Auth)getModel() appModels.IModel{
	return new(adminModels.Auth)
}

//Add 添加
func (this *Auth) Add(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.AddHandle(func() {
		auth := req.Model.(*adminModels.Auth)
		authValid.AuthSet(auth)
	})
}

//Delete 删除
func (this *Auth) Delete(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.DeleteHandle(func(ids []string) {
		for _, id := range ids {
			authValid.AuthRemove(id)
		}
	})
}

//Edit 修改
func (this *Auth) Edit(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.EditHandle(func() {
		auth := req.Model.(*adminModels.Auth)
		authValid.AuthSet(auth)
	})
}

func (this *Auth) List(r *ghttp.Request){
	this.NewRequest(r,this.getModel()).List()
}
//AuthList 获取需要指定权限才访问的菜单列表
func (this *Auth) AuthList(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	authGroupId := r.GetString("id")
	if authGroupId == "" {
		req.JsonError("请选择权限组")
	}
	if req.LoginUser.Account.AccountType == dataAuth.SYSTEM {
		req.LoginUser.User.AuthGroupId = authGroupId
	} else {
		if authGroupId != req.LoginUser.User.AuthGroupId {
			user := new(appModels.Users)
			has, err := orm.Db.Where(builder.Eq{"account_id": req.LoginUser.Account.Id, "auth_group_id": authGroupId}).Get(user)
			if err != nil {
				g.Log().Errorf("查询权限组【用户】信息失败，错误：%v", err)
				req.JsonError("获取菜单列表失败")
			}
			if !has {
				req.JsonError("您没有权限访问该【权限组】菜单列表")
			}
			req.LoginUser.User = *user
		}
	}
	authList := authValid.GetUserAuthList(req.LoginUser, false)
	list := make([]adminModels.Auth, 0)
	for _, v := range *authList {
		if v.Visit == dataAuth.AUTH && v.Disabled == 1 && v.AuthGroupId == authGroupId {
			list = append(list, v)
		}
	}
	req.JsonSuccessData(list)
}
